package com.baidu.service.impl;

import com.baidu.model.entity.UserModel;
import com.baidu.response.ResponseBody;
import com.baidu.service.InUserControllerService;
import com.until.request.RequestUtil;
import com.until.response.RestfulCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author user
 */
@Service
public class UserControllerServiceImpl implements InUserControllerService {
    @Autowired
    private UserServiceImpl userInfoImpl;

    @Autowired
    private RestfulCode restfulCode;

    @Autowired
    private RequestUtil requestUtil;

    @Autowired
    private ResponseBody responseBody;

    /**
     * 用户登录
     * @param username 用户名
     * @param userPassword 用户密码
     * @param response response 返回的信息
     * @return 返回相应信息
     */
    @Override
    public RestfulCode.CodeSatCode userLogin(String username, String userPassword, HttpServletResponse response) {
        Map<String,String> cookie= new HashMap<>(0);
        UserModel userInfo=null;
        RestfulCode.CodeSatCode userActionFailed = null;
        try {
            userActionFailed=responseBody.USER_OPERATION_SUCCEEDED;
            userInfo=userInfoImpl.userLogin(username,userPassword);
            userActionFailed.setMessage("用户登录成功");

            cookie.put("userid", String.valueOf(userInfo.getId()));
            requestUtil.addCookie(response,cookie);
        } catch (Exception e) {
            userActionFailed=responseBody.USER_ACTION_FAILED;
            userActionFailed.setMessage("用户登录失败,请检查填写的信息");
        }
        return restfulCode.getFreeResult(userActionFailed);
    }

    /**
     * 得到用户信息的controller实现
     * @param pathValue  path 中的 value 中的用户id
     * @return 得到用户信息
     */
    @Override
    public RestfulCode.CodeSatCode getUserInfo(Integer pathValue) {
        UserModel userInfo=null;
        RestfulCode.CodeSatCode userActionFailed = responseBody.USER_OPERATION_SUCCEEDED;
        try {
            userInfo=userInfoImpl.getUserInfo(pathValue);
            userInfo.setPassword(null);
            userActionFailed.setData(userInfo);
        } catch (Exception e) {
            userActionFailed = responseBody.NOT_FOUND_EXAMPLE;
        }
        return restfulCode.getFreeResult(userActionFailed);
    }
}
